#include <iostream>
#include <mysql++.h>
#include <iomanip>
#include <stdio.h>

#include <ListenSocket.h>
#include <SocketHandlerEp.h>
#include <TcpSocket.h>

#include "Connection.h"
#include "main.h"

using namespace std;

Database *dbSetting;
//Elements *elems;
//Cardsets *cardsets;

int main()
{
    //server variable
    int port;
    int max_conn;

    dbSetting = new Database();
    //dbSetting->setDb("db_ttpsp");
    //dbSetting->setServer("127.0.0.1:3306");
    //dbSetting->setUser("ttpsp");
    //dbSetting->setPass("kn1ghts0fth3r0und");
    dbSetting->setDb("db_ttpsp");
    dbSetting->setServer("127.0.0.1:3306");
    dbSetting->setUser("ttpsp");
    dbSetting->setPass("ttpsp");

    cout << "TripleTriad Server ...\n Avvio in corso!\n";

    //verifica connessione DB
    mysqlpp::Connection conn(false);
    if (conn.connect(dbSetting->getDb(), dbSetting->getServer(), dbSetting->getUser(), dbSetting->getPass())){
        cout << "Connessione al DB verificata\n";
        cout << "Caricamento impostazioni\n";
        mysqlpp::Query query = conn.query("SELECT TT_VAR_NUM FROM TT_VARIABLE WHERE TT_VAR_NAME = 'PORT_GAME'");
        if (mysqlpp::StoreQueryResult res = query.store()){
            if (res.num_rows()>0){
                /*TODO Controllare il valore della porta se inteno ai limiti*/
                port = res[0][0];
            }
            else
            {
                port = 9000;
            }
        }
        query.reset();
        mysqlpp::Query query1 = conn.query("SELECT TT_VAR_NUM FROM TT_VARIABLE WHERE TT_VAR_NAME = 'MAXCONN_GAME'");
        if (mysqlpp::StoreQueryResult res = query1.store()){
            if (res.num_rows()>0){
                max_conn = res[0][0];
            }
            else
            {
                max_conn = 20;
            }
        }
        query1.reset();
    } else {
        cout << "Connessione al DB non riuscita\n";
        exit(-15);
    }
    /*
    cout << "Estrazione Elements\n";
    elems = new Elements();
    elems->loadElem();


    cout << "Estrazione Cardsets\n";
    cardsets = new Cardsets();
    cardsets->loadCardsets();
    */

    cout << "Avvio del SERVER :\n\tPorta - " << port <<"\n\tConn MAX - " << max_conn << "\n";
    SocketHandler h;
    ListenSocket<Connection> l(h);
    if (l.Bind(port,max_conn))
    {
        printf("Impossibile aprire la porta %d\n",port);
        exit(-10);
    }
    cout << "Server pronto a ricevere connessioni... \n";
    h.Add(&l);//pone in ascolto il server
    h.Select(1,0);//aggiunge la connessione
    while (h.GetCount())//finché non è pieno il pool di connessioni
    {
        h.Select(1,0);//Aggiunge una connessione
    }
}
